import axios from 'axios'
import router from '../router'
import { ElMessage } from 'element-plus'

const baseURL = 'http://localhost:5000/api'

const api = axios.create({
  baseURL,
  timeout: 5000,
  withCredentials: true,
  headers: {
    'Content-Type': 'application/json',
    'Accept': 'application/json'
  }
})

// 请求拦截器
api.interceptors.request.use(
  config => {
    const token = localStorage.getItem('token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
api.interceptors.response.use(
  response => response.data,
  error => {
    if (error.response) {
      switch (error.response.status) {
        case 401:
          // 未登录或 token 过期
          localStorage.removeItem('token')
          localStorage.removeItem('userRole')
          localStorage.removeItem('username')
          router.push('/login')
          break
        case 403:
          // 权限不足
          ElMessage.error('权限不足')
          break
        default:
          ElMessage.error(error.response.data.message || '请求失败')
      }
    }
    return Promise.reject(error)
  }
)

// 用户相关接口
export const userApi = {
  register: (data) => api.post('/register', data),
  login: (data) => api.post('/login', data),
  getUsers: () => api.get('/users'),
  deleteUser: (id) => api.delete(`/users/${id}`)
}

// 房源相关接口
export const houseApi = {
  getHouses: () => api.get('/houses'),
  getHouse: (id) => api.get(`/houses/${id}`),
  createHouse: (data) => api.post('/houses', data),
  updateHouse: (id, data) => api.put(`/houses/${id}`, data),
  deleteHouse: (id) => api.delete(`/houses/${id}`),
  getLandlordHouses: () => api.get('/landlord/houses'),
  
  // 智能搜索相关接口
  searchByRegion: (region) => api.get(`/houses/search/region?region=${encodeURIComponent(region)}`),
  searchByType: (type) => api.get(`/houses/search/type?type=${encodeURIComponent(type)}`),
  searchHouses: (params) => {
    const queryString = new URLSearchParams(params).toString()
    return api.get(`/houses/search?${queryString}`)
  },
  getHouseDetail: (id) => api.get(`/houses/${id}/detail`),
  
  // 房源状态管理
  updateHouseStatus: (id, status) => api.put(`/houses/${id}/status`, { status }),
  getStatistics: () => api.get('/houses/statistics')
}

// 消息相关接口
export const newsApi = {
  getNews: () => api.get('/news'),
  createNews: (data) => api.post('/news', data),
  updateNews: (id, data) => api.put(`/news/${id}`, data),
  deleteNews: (id) => api.delete(`/news/${id}`)
}

export const uploadApi = {
  upload: (file) => {
    const formData = new FormData()
    formData.append('file', file)
    return api.post('/upload', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
  }
}

export default api 